<template>
  <!-- 弹窗模式 -->
  <el-drawer
    v-if="mode === 'drawer'"
    v-model="drawerVisible"
    :title="title"
    :size="size"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="form-container">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :label-width="labelWidth"
        :label-position="labelPosition"
        class="common-form"
      >
        <!-- 使用栅格系统实现多列布局 -->
        <el-row :gutter="gutter">
          <template v-for="field in fields" :key="field.prop">
            <el-col :span="getColSpan(field)">
          <!-- 文本输入框 -->
          <el-form-item
            v-if="field.type === 'input'"
            :label="field.label"
            :prop="field.prop"
            :required="field.required"
          >
            <el-input
              v-model="formData[field.prop]"
              :placeholder="field.placeholder || `请输入${field.label}`"
              :disabled="field.disabled"
              :maxlength="field.maxlength"
              :show-word-limit="field.showWordLimit"
              :clearable="field.clearable !== false"
              @change="(val) => handleFieldChange(field.prop, val)"
              @blur="(event) => handleFieldBlur(field.prop, event.target.value)"
              @focus="(event) => handleFieldFocus(field.prop, event.target.value)"
            />
          </el-form-item>

          <!-- 密码输入框 -->
          <el-form-item
            v-else-if="field.type === 'password'"
            :label="field.label"
            :prop="field.prop"
            :required="field.required"
          >
            <el-input
              v-model="formData[field.prop]"
              type="password"
              :placeholder="field.placeholder || `请输入${field.label}`"
              :disabled="field.disabled"
              :maxlength="field.maxlength"
              :show-password="field.showPassword !== false"
              :clearable="field.clearable !== false"
              @change="(val) => handleFieldChange(field.prop, val)"
              @blur="(event) => handleFieldBlur(field.prop, event.target.value)"
              @focus="(event) => handleFieldFocus(field.prop, event.target.value)"
            />
          </el-form-item>

          <!-- 数字输入框 -->
          <el-form-item
            v-else-if="field.type === 'number'"
            :label="field.label"
            :prop="field.prop"
            :required="field.required"
          >
            <el-input-number
              v-model="formData[field.prop]"
              :placeholder="field.placeholder || `请输入${field.label}`"
              :disabled="field.disabled"
              :min="field.min"
              :max="field.max"
              :step="field.step || 1"
              :precision="field.precision"
              style="width: 100%"
              @change="(val) => handleFieldChange(field.prop, val)"
              @blur="() => handleFieldBlur(field.prop, formData[field.prop])"
              @focus="() => handleFieldFocus(field.prop, formData[field.prop])"
            />
          </el-form-item>

          <!-- 下拉选择框 -->
          <el-form-item
            v-else-if="field.type === 'select'"
            :label="field.label"
            :prop="field.prop"
            :required="field.required"
          >
            <el-select
              v-model="formData[field.prop]"
              :placeholder="field.placeholder || `请选择${field.label}`"
              :disabled="field.disabled"
              :multiple="field.multiple"
              :clearable="field.clearable !== false"
              style="width: 100%"
              @change="(val) => handleFieldChange(field.prop, val)"
              @blur="() => handleFieldBlur(field.prop, formData[field.prop])"
              @focus="() => handleFieldFocus(field.prop, formData[field.prop])"
            >
              <el-option
                v-for="option in field.options"
                :key="option.value"
                :label="option.label"
                :value="option.value"
                :disabled="option.disabled"
              />
            </el-select>
          </el-form-item>

          <!-- 单选框组 -->
          <el-form-item
            v-else-if="field.type === 'radio'"
            :label="field.label"
            :prop="field.prop"
            :required="field.required"
          >
            <el-radio-group
              v-model="formData[field.prop]"
              :disabled="field.disabled"
              @change="(val) => handleFieldChange(field.prop, val)"
            >
              <el-radio
                v-for="option in field.options"
                :key="option.value"
                :label="option.value"
                :disabled="option.disabled"
              >
                {{ option.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 复选框组 -->
          <el-form-item
            v-else-if="field.type === 'checkbox'"
            :label="field.label"
            :prop="field.prop"
            :required="field.required"
          >
            <el-checkbox-group
              v-model="formData[field.prop]"
              :disabled="field.disabled"
              @change="(val) => handleFieldChange(field.prop, val)"
            >
              <el-checkbox
                v-for="option in field.options"
                :key="option.value"
                :label="option.value"
                :disabled="option.disabled"
              >
                {{ option.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <!-- 日期选择器 -->
          <el-form-item
            v-else-if="field.type === 'date'"
            :label="field.label"
            :prop="field.prop"
            :required="field.required"
          >
            <el-date-picker
              v-model="formData[field.prop]"
              type="date"
              :placeholder="field.placeholder || `请选择${field.label}`"
              :disabled="field.disabled"
              :format="field.format || 'YYYY-MM-DD'"
              :value-format="field.valueFormat || 'YYYY-MM-DD'"
              :clearable="field.clearable !== false"
              style="width: 100%"
              @change="(val) => handleFieldChange(field.prop, val)"
              @blur="() => handleFieldBlur(field.prop, formData[field.prop])"
              @focus="() => handleFieldFocus(field.prop, formData[field.prop])"
            />
          </el-form-item>

          <!-- 日期时间选择器 -->
          <el-form-item
            v-else-if="field.type === 'datetime'"
            :label="field.label"
            :prop="field.prop"
            :required="field.required"
          >
            <el-date-picker
              v-model="formData[field.prop]"
              type="datetime"
              :placeholder="field.placeholder || `请选择${field.label}`"
              :disabled="field.disabled"
              :format="field.format || 'YYYY-MM-DD HH:mm:ss'"
              :value-format="field.valueFormat || 'YYYY-MM-DD HH:mm:ss'"
              :clearable="field.clearable !== false"
              style="width: 100%"
              @change="(val) => handleFieldChange(field.prop, val)"
              @blur="() => handleFieldBlur(field.prop, formData[field.prop])"
              @focus="() => handleFieldFocus(field.prop, formData[field.prop])"
            />
          </el-form-item>

          <!-- 文本域 -->
          <el-form-item
            v-else-if="field.type === 'textarea'"
            :label="field.label"
            :prop="field.prop"
            :required="field.required"
          >
            <el-input
              v-model="formData[field.prop]"
              type="textarea"
              :placeholder="field.placeholder || `请输入${field.label}`"
              :disabled="field.disabled"
              :maxlength="field.maxlength"
              :show-word-limit="field.showWordLimit"
              :rows="field.rows || 4"
              :autosize="field.autosize"
              @change="(val) => handleFieldChange(field.prop, val)"
              @blur="(event) => handleFieldBlur(field.prop, event.target.value)"
              @focus="(event) => handleFieldFocus(field.prop, event.target.value)"
            />
          </el-form-item>

          <!-- 开关 -->
          <el-form-item
            v-else-if="field.type === 'switch'"
            :label="field.label"
            :prop="field.prop"
            :required="field.required"
          >
            <el-switch
              v-model="formData[field.prop]"
              :disabled="field.disabled"
              :active-text="field.activeText"
              :inactive-text="field.inactiveText"
              :active-value="field.activeValue !== undefined ? field.activeValue : true"
              :inactive-value="field.inactiveValue !== undefined ? field.inactiveValue : false"
              @change="(val) => handleFieldChange(field.prop, val)"
            />
          </el-form-item>

          <!-- 表格类型 -->
          <el-form-item
            v-else-if="field.type === 'table'"
            :label="field.label"
            :prop="field.prop"
            :required="field.required"
            class="table-form-item"
          >
            <div class="table-container">
              <!-- 表格操作按钮 -->
              <div v-if="field.buttons && field.buttons.length > 0" class="table-actions" style="margin-bottom: 10px;">
                <template v-for="button in field.buttons" :key="button.type">
                  <el-button
                    v-if="button.visible !== false"
                    :type="button.type === 'primary' ? 'primary' : 'default'"
                    :disabled="button.disabled"
                    size="small"
                    @click="handleTableButtonClick(button, field)"
                  >
                    <el-icon v-if="button.icon" >
                      <component :is="button.icon" />
                    </el-icon>
                    {{ button.text }}
                  </el-button>
                </template>
              </div>
              <el-table
                :data="formData[field.prop] || []"
                border
                style="width: 100%"
                size="small"
              >
                <el-table-column
                  v-for="column in field.columns"
                  :key="column.prop"
                  :prop="column.prop"
                  :label="column.label"
                  :width="column.width"
                >
                  <template #default="{ row, $index }">
                    <!-- 输入框 -->
                    <el-input
                      v-if="column.type === 'input'"
                      v-model="row[column.prop]"
                      :placeholder="column.placeholder"
                      size="small"
                      @change="() => handleTableCellChange(field.prop, $index, column.prop, row[column.prop])"
                    />
                    <!-- 数字输入框 -->
                    <el-input-number
                      v-else-if="column.type === 'number'"
                      v-model="row[column.prop]"
                      :min="column.min"
                      :max="column.max"
                      size="small"
                      style="width: 100%"
                      @change="() => handleTableCellChange(field.prop, $index, column.prop, row[column.prop])"
                    />
                    <!-- 下拉选择 -->
                    <el-select
                      v-else-if="column.type === 'select'"
                      v-model="row[column.prop]"
                      :placeholder="column.placeholder"
                      size="small"
                      style="width: 100%"
                      @change="() => handleTableCellChange(field.prop, $index, column.prop, row[column.prop])"
                    >
                      <el-option
                        v-for="option in column.options"
                        :key="option.value"
                        :label="option.label"
                        :value="option.value"
                      />
                    </el-select>
                    <!-- 日期选择 -->
                    <el-date-picker
                      v-else-if="column.type === 'date'"
                      v-model="row[column.prop]"
                      type="date"
                      size="small"
                      style="width: 100%"
                      @change="() => handleTableCellChange(field.prop, $index, column.prop, row[column.prop])"
                    />
                    <!-- 开关 -->
                    <el-switch
                      v-else-if="column.type === 'switch'"
                      v-model="row[column.prop]"
                      :active-text="column.activeText"
                      :inactive-text="column.inactiveText"
                      :active-value="column.activeValue !== undefined ? column.activeValue : true"
                      :inactive-value="column.inactiveValue !== undefined ? column.inactiveValue : false"
                      size="small"
                      @change="() => handleTableCellChange(field.prop, $index, column.prop, row[column.prop])"
                    />
                  </template>
                </el-table-column>
                <!-- 操作列 -->
                <el-table-column 
                  v-if="field.showOperationColumn !== false"
                  :label="field.operationColumnLabel || '操作'" 
                  :width="field.operationColumnWidth || 80" 
                  fixed="right"
                >
                  <template #default="{ $index }">
                    <el-button
                      type="danger"
                      size="small"
                      text
                      :disabled="field.disableDeleteFirstRow && $index === 0"
                      @click="removeTableRow(field.prop, $index)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>

          <!-- 自定义插槽 -->
          <el-form-item
            v-else-if="field.type === 'slot'"
            :label="field.label"
            :prop="field.prop"
            :required="field.required"
          >
            <slot :name="field.prop" :field="field" :form-data="formData" />
          </el-form-item>
            </el-col>
          </template>
        </el-row>
      </el-form>
    </div>

    <template #footer>
      <div class="form-footer">
        <slot name="extraButtons"/>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ submitText }}
        </el-button>
      </div>
    </template>
  </el-drawer>

  <!-- 页面模式 -->
  <div v-else-if="mode === 'page'" class="common-page-form">
    <!-- 页面标题 -->
    <div v-if="showHeader" class="form-header">
      <h2>{{ title }}</h2>
      <p v-if="description">{{ description }}</p>
    </div>

    <!-- 表单内容 -->
    <div class="form-content">
      <el-form
        ref="pageFormRef"
        :model="formData"
        :rules="formRules"
        :label-width="labelWidth"
        :label-position="labelPosition"
        class="page-form"
      >
        <!-- 使用栅格系统实现多列布局 -->
         <el-row :gutter="gutter">
           <template v-for="field in fields" :key="field.prop">
             <el-col :span="getColSpan(field)">
               <!-- 文本输入框 -->
               <el-form-item
                 v-if="field.type === 'input'"
                 :label="field.label"
                 :prop="field.prop"
                 :required="field.required"
               >
                 <el-input
                   v-model="formData[field.prop]"
                   :placeholder="field.placeholder || `请输入${field.label}`"
                   :disabled="field.disabled"
                   :maxlength="field.maxlength"
                   :show-word-limit="field.showWordLimit"
                   :clearable="field.clearable !== false"
                   @change="(val) => handleFieldChange(field.prop, val)"
                   @blur="(event) => handleFieldBlur(field.prop, event.target.value)"
                   @focus="(event) => handleFieldFocus(field.prop, event.target.value)"
                 />
               </el-form-item>

               <!-- 密码输入框 -->
               <el-form-item
                 v-else-if="field.type === 'password'"
                 :label="field.label"
                 :prop="field.prop"
                 :required="field.required"
               >
                 <el-input
                   v-model="formData[field.prop]"
                   type="password"
                   :placeholder="field.placeholder || `请输入${field.label}`"
                   :disabled="field.disabled"
                   :maxlength="field.maxlength"
                   :show-password="field.showPassword !== false"
                   :clearable="field.clearable !== false"
                   @change="(val) => handleFieldChange(field.prop, val)"
                   @blur="(event) => handleFieldBlur(field.prop, event.target.value)"
                   @focus="(event) => handleFieldFocus(field.prop, event.target.value)"
                 />
               </el-form-item>

               <!-- 数字输入框 -->
               <el-form-item
                 v-else-if="field.type === 'number'"
                 :label="field.label"
                 :prop="field.prop"
                 :required="field.required"
               >
                 <el-input-number
                   v-model="formData[field.prop]"
                   :placeholder="field.placeholder || `请输入${field.label}`"
                   :disabled="field.disabled"
                   :min="field.min"
                   :max="field.max"
                   :step="field.step || 1"
                   :precision="field.precision"
                   style="width: 100%"
                   @change="(val) => handleFieldChange(field.prop, val)"
                   @blur="() => handleFieldBlur(field.prop, formData[field.prop])"
                   @focus="() => handleFieldFocus(field.prop, formData[field.prop])"
                 />
               </el-form-item>

               <!-- 下拉选择框 -->
               <el-form-item
                 v-else-if="field.type === 'select'"
                 :label="field.label"
                 :prop="field.prop"
                 :required="field.required"
               >
                 <el-select
                   v-model="formData[field.prop]"
                   :placeholder="field.placeholder || `请选择${field.label}`"
                   :disabled="field.disabled"
                   :multiple="field.multiple"
                   :clearable="field.clearable !== false"
                   style="width: 100%"
                   @change="(val) => handleFieldChange(field.prop, val)"
                   @blur="() => handleFieldBlur(field.prop, formData[field.prop])"
                   @focus="() => handleFieldFocus(field.prop, formData[field.prop])"
                 >
                   <el-option
                     v-for="option in field.options"
                     :key="option.value"
                     :label="option.label"
                     :value="option.value"
                     :disabled="option.disabled"
                   />
                 </el-select>
               </el-form-item>

               <!-- 单选框组 -->
               <el-form-item
                 v-else-if="field.type === 'radio'"
                 :label="field.label"
                 :prop="field.prop"
                 :required="field.required"
               >
                 <el-radio-group
                   v-model="formData[field.prop]"
                   :disabled="field.disabled"
                   @change="(val) => handleFieldChange(field.prop, val)"
                 >
                   <el-radio
                     v-for="option in field.options"
                     :key="option.value"
                     :label="option.value"
                     :disabled="option.disabled"
                   >
                     {{ option.label }}
                   </el-radio>
                 </el-radio-group>
               </el-form-item>

               <!-- 复选框组 -->
               <el-form-item
                 v-else-if="field.type === 'checkbox'"
                 :label="field.label"
                 :prop="field.prop"
                 :required="field.required"
               >
                 <el-checkbox-group
                   v-model="formData[field.prop]"
                   :disabled="field.disabled"
                   @change="(val) => handleFieldChange(field.prop, val)"
                 >
                   <el-checkbox
                     v-for="option in field.options"
                     :key="option.value"
                     :label="option.value"
                     :disabled="option.disabled"
                   >
                     {{ option.label }}
                   </el-checkbox>
                 </el-checkbox-group>
               </el-form-item>

               <!-- 日期选择器 -->
               <el-form-item
                 v-else-if="field.type === 'date'"
                 :label="field.label"
                 :prop="field.prop"
                 :required="field.required"
               >
                 <el-date-picker
                   v-model="formData[field.prop]"
                   type="date"
                   :placeholder="field.placeholder || `请选择${field.label}`"
                   :disabled="field.disabled"
                   :format="field.format || 'YYYY-MM-DD'"
                   :value-format="field.valueFormat || 'YYYY-MM-DD'"
                   :clearable="field.clearable !== false"
                   style="width: 100%"
                   @change="(val) => handleFieldChange(field.prop, val)"
                   @blur="() => handleFieldBlur(field.prop, formData[field.prop])"
                   @focus="() => handleFieldFocus(field.prop, formData[field.prop])"
                 />
               </el-form-item>

               <!-- 日期时间选择器 -->
               <el-form-item
                 v-else-if="field.type === 'datetime'"
                 :label="field.label"
                 :prop="field.prop"
                 :required="field.required"
               >
                 <el-date-picker
                   v-model="formData[field.prop]"
                   type="datetime"
                   :placeholder="field.placeholder || `请选择${field.label}`"
                   :disabled="field.disabled"
                   :format="field.format || 'YYYY-MM-DD HH:mm:ss'"
                   :value-format="field.valueFormat || 'YYYY-MM-DD HH:mm:ss'"
                   :clearable="field.clearable !== false"
                   style="width: 100%"
                   @change="(val) => handleFieldChange(field.prop, val)"
                   @blur="() => handleFieldBlur(field.prop, formData[field.prop])"
                   @focus="() => handleFieldFocus(field.prop, formData[field.prop])"
                 />
               </el-form-item>

               <!-- 文本域 -->
               <el-form-item
                 v-else-if="field.type === 'textarea'"
                 :label="field.label"
                 :prop="field.prop"
                 :required="field.required"
               >
                 <el-input
                   v-model="formData[field.prop]"
                   type="textarea"
                   :placeholder="field.placeholder || `请输入${field.label}`"
                   :disabled="field.disabled"
                   :rows="field.rows || 4"
                   :maxlength="field.maxlength"
                   :show-word-limit="field.showWordLimit"
                   :resize="field.resize || 'vertical'"
                   @change="(val) => handleFieldChange(field.prop, val)"
                   @blur="(event) => handleFieldBlur(field.prop, event.target.value)"
                   @focus="(event) => handleFieldFocus(field.prop, event.target.value)"
                 />
               </el-form-item>

               <!-- 开关 -->
               <el-form-item
                 v-else-if="field.type === 'switch'"
                 :label="field.label"
                 :prop="field.prop"
                 :required="field.required"
               >
                 <el-switch
                   v-model="formData[field.prop]"
                   :disabled="field.disabled"
                   :active-text="field.activeText"
                   :inactive-text="field.inactiveText"
                   :active-value="field.activeValue !== undefined ? field.activeValue : true"
                   :inactive-value="field.inactiveValue !== undefined ? field.inactiveValue : false"
                   @change="(val) => handleFieldChange(field.prop, val)"
                 />
               </el-form-item>

               <!-- 表格类型 -->
               <el-form-item
                 v-else-if="field.type === 'table'"
                 :label="field.label"
                 :prop="field.prop"
                 :required="field.required"
                 class="table-form-item"
               >
                 <div class="table-container">
                   <!-- 表格操作按钮 -->
                   <div v-if="field.buttons && field.buttons.length > 0" class="table-actions" style="margin-bottom: 10px;">
                     <template v-for="button in field.buttons" :key="button.type">
                       <el-button
                         v-if="button.visible !== false"
                         :type="button.type === 'add-row' ? 'primary' : 'default'"
                         :disabled="button.disabled"
                         size="small"
                         @click="handleTableButtonClick(button, field)"
                       >
                         <el-icon v-if="button.icon" :class="button.icon" />
                         {{ button.text }}
                       </el-button>
                     </template>
                   </div>
                   <el-table
                     :data="formData[field.prop] || []"
                     border
                     style="width: 100%"
                     size="small"
                   >
                     <el-table-column
                       v-for="column in field.columns"
                       :key="column.prop"
                       :prop="column.prop"
                       :label="column.label"
                       :width="column.width"
                     >
                       <template #default="{ row, $index }">
                         <!-- 输入框 -->
                         <el-input
                           v-if="column.type === 'input'"
                           v-model="row[column.prop]"
                           :placeholder="column.placeholder"
                           size="small"
                           @change="() => handleTableCellChange(field.prop, $index, column.prop, row[column.prop])"
                         />
                         <!-- 数字输入框 -->
                         <el-input-number
                           v-else-if="column.type === 'number'"
                           v-model="row[column.prop]"
                           :min="column.min"
                           :max="column.max"
                           size="small"
                           style="width: 100%"
                           @change="() => handleTableCellChange(field.prop, $index, column.prop, row[column.prop])"
                         />
                         <!-- 下拉选择 -->
                         <el-select
                           v-else-if="column.type === 'select'"
                           v-model="row[column.prop]"
                           :placeholder="column.placeholder"
                           size="small"
                           style="width: 100%"
                           @change="() => handleTableCellChange(field.prop, $index, column.prop, row[column.prop])"
                         >
                           <el-option
                             v-for="option in column.options"
                             :key="option.value"
                             :label="option.label"
                             :value="option.value"
                           />
                         </el-select>
                         <!-- 日期选择 -->
                         <el-date-picker
                           v-else-if="column.type === 'date'"
                           v-model="row[column.prop]"
                           type="date"
                           size="small"
                           style="width: 100%"
                           @change="() => handleTableCellChange(field.prop, $index, column.prop, row[column.prop])"
                         />
                         <!-- 开关 -->
                         <el-switch
                           v-else-if="column.type === 'switch'"
                           v-model="row[column.prop]"
                           :active-text="column.activeText"
                           :inactive-text="column.inactiveText"
                           :active-value="column.activeValue !== undefined ? column.activeValue : true"
                           :inactive-value="column.inactiveValue !== undefined ? column.inactiveValue : false"
                           size="small"
                           @change="() => handleTableCellChange(field.prop, $index, column.prop, row[column.prop])"
                         />
                       </template>
                     </el-table-column>
                     <!-- 操作列 -->
                     <el-table-column 
                       v-if="field.showOperationColumn !== false"
                       :label="field.operationColumnLabel || '操作'" 
                       :width="field.operationColumnWidth || 80" 
                       fixed="right"
                     >
                       <template #default="{ $index }">
                         <el-button
                           type="danger"
                           size="small"
                           text
                           :disabled="field.disableDeleteFirstRow && $index === 0"
                           @click="removeTableRow(field.prop, $index)"
                         >
                           删除
                         </el-button>
                       </template>
                     </el-table-column>
                   </el-table>
                 </div>
               </el-form-item>

               <!-- 自定义插槽 -->
               <el-form-item
                 v-else-if="field.type === 'slot'"
                 :label="field.label"
                 :prop="field.prop"
                 :required="field.required"
               >
                 <slot
                   :name="field.slotName || field.prop"
                   :field="field"
                   :value="formData[field.prop]"
                   :form-data="formData"
                   :on-change="(val: any) => handleFieldChange(field.prop, val)"
                 />
               </el-form-item>
             </el-col>
           </template>
         </el-row>
      </el-form>
    </div>

    <!-- 页面底部操作按钮 -->
    <div v-if="showFooter" class="form-footer page-footer">
      <slot name="extraButtons"/>
      <el-button v-if="showCancel" @click="handleCancel">{{ cancelText }}</el-button>
      <el-button v-if="showReset" @click="handleReset">{{ resetText }}</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">
        {{ submitText }}
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import {computed, reactive, ref, watch} from 'vue'
import type {FormInstance, FormRules} from 'element-plus'
import {ElMessage} from 'element-plus'
import type {Emits, FormField, PropsConfig} from './types'


const props = withDefaults(defineProps<PropsConfig>(), {
  visible: false,
  mode: 'drawer',
  title: '表单',
  description: '',
  data: () => ({}),
  config: () => ({}),
  loading: false,
  submitText: '确定',
  cancelText: '取消',
  resetText: '重置',
  showHeader: true,
  showFooter: true,
  showCancel: true,
  showReset: true,
  columnsPerRow: 2,
  gutter: 20
})

const emit = defineEmits<Emits>()

// Refs
const formRef = ref<FormInstance>()
const pageFormRef = ref<FormInstance>()
const formData = reactive<Record<string, any>>({})

// Computed
const drawerVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const size = computed(() => props.config?.size || '50%')
const labelWidth = computed(() => props.config?.labelWidth || '100px')
const labelPosition = computed(() => props.config?.labelPosition || 'right')

// 获取当前表单引用
const currentFormRef = computed(() => {
  return props.mode === 'page' ? pageFormRef.value : formRef.value
})

// 计算列跨度
const getColSpan = (field: FormField) => {
  // table类型始终占据整行
  if (field.type === 'table') {
    return 24
  }
  if (field.colSpan) {
    return field.colSpan
  }
  return Math.floor(24 / props.columnsPerRow)
}

// 动态生成表单验证规则
const formRules = computed(() => {
  const rules: FormRules = {}
  
  props.fields.forEach(field => {
    if (field.rules) {
      rules[field.prop] = field.rules
    } else if (field.required) {
      // 默认必填规则
      const message = field.requiredMessage || `请${getRequiredMessage(field.type)}${field.label}`
      rules[field.prop] = [{ required: true, message, trigger: getValidateTrigger(field.type) }]
    }
  })
  
  // 特殊处理确认密码字段
  if (rules.confirmPassword) {
    const existingRules = Array.isArray(rules.confirmPassword) ? rules.confirmPassword : [rules.confirmPassword]
    rules.confirmPassword = [
      ...existingRules,
      {
        validator: (rule: any, value: any, callback: any) => {
          if (value === '') {
            callback()
          } else if (value !== formData.password) {
            callback(new Error('两次输入的密码不一致'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ]
  }
  return rules
})

// 获取必填提示文字
const getRequiredMessage = (type: string) => {
  const messageMap: Record<string, string> = {
    input: '输入',
    password: '输入',
    number: '输入',
    textarea: '输入',
    select: '选择',
    radio: '选择',
    checkbox: '选择',
    date: '选择',
    datetime: '选择',
    switch: '选择',
    table: '填写'
  }
  return messageMap[type] || '输入'
}

// 获取验证触发方式
const getValidateTrigger = (type: string) => {
  const triggerMap: Record<string, string> = {
    input: 'blur',
    password: 'blur',
    number: 'blur',
    textarea: 'blur',
    select: 'change',
    radio: 'change',
    checkbox: 'change',
    date: 'change',
    datetime: 'change',
    switch: 'change',
    table: 'change'
  }
  return triggerMap[type] || 'blur'
}

// 初始化表单数据
const initFormData = () => {
  // 清空表单数据
  Object.keys(formData).forEach(key => {
    delete formData[key]
  })
  
  // 设置字段默认值
  props.fields.forEach(field => {
    if (field.defaultValue !== undefined) {
      formData[field.prop] = field.defaultValue
    } else {
      // 根据字段类型设置默认值
      switch (field.type) {
        case 'checkbox':
          formData[field.prop] = []
          break
        case 'switch':
          formData[field.prop] = field.activeValue !== undefined ? field.inactiveValue : false
          break
        case 'table':
          formData[field.prop] = []
          break
        default:
          formData[field.prop] = ''
      }
    }
  })
  
  // 合并传入的数据
  if (props.data && Object.keys(props.data).length > 0) {
    Object.assign(formData, props.data)
  }
}

// 监听数据变化
watch(
  () => [props.visible, props.data],
  ([visible, data]) => {
    if (visible) {
      initFormData()
    }
  },
  { immediate: true, deep: true }
)

// 处理关闭
const handleClose = () => {
  formRef.value?.clearValidate()
  emit('close')
  emit('update:visible', false)
}



// 处理字段变化
const handleFieldChange = (prop: string, value: any) => {
  // 查找对应的字段配置
  const field = props.fields.find(f => f.prop === prop)
  
  // 执行字段自定义变化回调
  if (field?.onChange) {
    field.onChange(value, { ...formData })
  }
  props.data[prop] = value;
  emit('field-change', prop, value, { ...formData })
}

// 处理字段失焦
const handleFieldBlur = (prop: string, value: any) => {
  // 查找对应的字段配置
  const field = props.fields.find(f => f.prop === prop)
  
  // 执行字段自定义失焦回调
  if (field?.onBlur) {
    field.onBlur(value, { ...formData })
  }
  
  emit('field-blur', prop, value, { ...formData })
}

// 处理字段聚焦
const handleFieldFocus = (prop: string, value: any) => {
  // 查找对应的字段配置
  const field = props.fields.find(f => f.prop === prop)
  
  // 执行字段自定义聚焦回调
  if (field?.onFocus) {
    field.onFocus(value, { ...formData })
  }
  
  emit('field-focus', prop, value, { ...formData })
}

// 处理提交
const handleSubmit = async () => {
  const form = currentFormRef.value
  if (!form) return
  
  try {
    await form.validate()
    emit('submit', { ...formData })
  } catch (error) {
    ElMessage.error('请检查表单填写是否正确')
  }
}

// 处理取消（页面模式）
const handleCancel = () => {
  emit('cancel')
}

// 处理重置（页面模式）
const handleReset = () => {
  const form = currentFormRef.value
  if (form) {
    form.resetFields()
    initFormData()
  }
  emit('reset')
}

// 表格相关方法
const handleTableCellChange = (fieldProp: string, rowIndex: number, columnProp: string, value: any) => {
  // 触发字段变化事件
  emit('field-change', {
    field: fieldProp,
    value: formData[fieldProp],
    rowIndex,
    columnProp,
    cellValue: value
  })
}


const removeTableRow = (fieldProp: string, rowIndex: number) => {
  if (formData[fieldProp] && formData[fieldProp].length > rowIndex) {
    // 检查是否禁用删除第一行
    const field = props.fields.find(f => f.prop === fieldProp)
    if (field?.disableDeleteFirstRow && rowIndex === 0) {
      ElMessage.warning('第一行不允许删除')
      return
    }
    
    const removedRow = formData[fieldProp].splice(rowIndex, 1)[0]
    
    // 触发删除行事件
    emit('remove-row', {
      field: fieldProp,
      row: removedRow,
      index: rowIndex
    })
  }
}

// 处理表格按钮点击
const handleTableButtonClick = (button: any, field: FormField) => {
  // 优先调用配置中的 onClick 事件
  if (button.onClick) {
    button.onClick(formData[field.prop] || [], field.prop)
    return
  }
  
}

// 暴露方法
defineExpose({
  validate: () => currentFormRef.value?.validate(),
  resetFields: () => currentFormRef.value?.resetFields(),
  clearValidate: () => currentFormRef.value?.clearValidate(),
  getFormData: () => ({ ...formData }),
  handleReset,
  removeTableRow,
  handleTableButtonClick
})
</script>

<style scoped>
/* 弹窗模式样式 */
.form-container {
  padding: 20px;
  height: calc(83vh);
  overflow-y: auto;
}

.common-form {
}

.form-footer {
  padding: 20px;
  text-align: right;
  border-top: 1px solid #e4e7ed;
}

.form-footer .el-button {
  margin-left: 10px;
}

/* 页面模式样式 */
.common-page-form {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.form-header h2 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.form-header p {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.form-content {
  margin-bottom: 24px;
}

.page-form {
  width: 100%;
}

.page-footer {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

.page-footer .el-button {
  margin: 0 8px;
  min-width: 80px;
}

/* 通用样式 */
:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input),
:deep(.el-select),
:deep(.el-date-picker) {
  width: 100%;
}

/* 表格表单项样式 */
.table-form-item {
  width: 100%;
}

.table-form-item :deep(.el-form-item__content) {
  width: 100%;
}

.table-container {
  width: 100%;
  padding: 10px;
}

.table-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-start;
}

.table-actions .el-button {
  margin: 0;
}

/* 页面模式响应式 */
@media (max-width: 768px) {
  .common-page-form {
    padding: 16px;
    margin: 0;
    border-radius: 0;
    box-shadow: none;
  }
  
  .page-footer {
    text-align: center;
  }
  
  .page-footer .el-button {
    margin: 4px;
    width: 100px;
  }
}
</style>